/**
 * 退款相关控制器
 * 处理提前/延后离场、退款查询等功能
 */

const { query } = require('../config/db');
const refundCalculator = require('../utils/refundCalculator');
const WechatPayService = require('../services/WechatPayService');

/**
 * 格式化日期时间为MySQL格式
 * @param {string} dateTimeString - ISO日期时间字符串
 * @returns {string} MySQL格式的日期时间字符串
 */
function formatDateTimeForMySQL(dateTimeString) {
  if (!dateTimeString) return null;

  const date = new Date(dateTimeString);
  if (isNaN(date.getTime())) return null;

  // 转换为 YYYY-MM-DD HH:MM:SS 格式
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * 处理提前离场退款
 */
const processEarlyDeparture = async (req, res) => {
  try {
    const { orderId } = req.params;
    const { actual_end_time, reason } = req.body;
    const userId = req.user.id;

    console.log(`🚪 处理提前离场 - 订单ID: ${orderId}, 用户ID: ${userId}`);

    // 验证订单
    const orderQuery = `
      SELECT 
        id, order_number, status, final_amount, total_amount, discount_amount,
        planned_start_time, planned_end_time, actual_start_time, actual_end_time,
        parking_lot_id, transaction_id, payment_method, paid_at, user_coupon_id
      FROM orders
      WHERE id = ? AND user_id = ?
    `;

    const orders = await query(orderQuery, [orderId, userId]);

    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在或无权限访问'
      });
    }

    const order = orders[0];

    // 检查订单状态
    if (order.status !== 'in_progress') {
      return res.status(400).json({
        success: false,
        message: '只有进行中的订单才能申请提前离场退款'
      });
    }

    // 检查是否已经有实际离场时间
    if (order.actual_end_time) {
      return res.status(400).json({
        success: false,
        message: '订单已完成，无法申请提前离场退款'
      });
    }

    const actualEndTime = new Date(actual_end_time);
    const plannedEndTime = new Date(order.planned_end_time);

    // 检查是否确实是提前离场
    if (actualEndTime >= plannedEndTime) {
      return res.status(400).json({
        success: false,
        message: '实际离场时间不早于计划时间，无需申请提前离场退款'
      });
    }

    // 计算退款金额
    const refundResult = await refundCalculator.calculateEarlyDepartureRefund(order, actualEndTime);

    if (!refundResult.success) {
      return res.status(400).json({
        success: false,
        message: `退款计算失败: ${refundResult.error}`
      });
    }

    let refundInfo = null;

    // 如果有退款金额，处理退款
    if (refundResult.refundAmount > 0) {
      // 生成退款单号
      const refundNumber = refundCalculator.generateRefundNumber(order.order_number, 'ED');
      
      // 调用微信支付退款接口
      const wechatRefundResult = await WechatPayService.refund({
        transactionId: order.transaction_id,
        outRefundNo: refundNumber,
        reason: reason || refundResult.refundReason,
        refundAmount: refundResult.refundAmount,
        totalAmount: parseFloat(order.final_amount)
      });

      if (!wechatRefundResult.success) {
        return res.status(400).json({
          success: false,
          message: `退款申请失败: ${wechatRefundResult.error}`
        });
      }

      refundInfo = {
        refund_number: refundNumber,
        refund_amount: refundResult.refundAmount,
        refund_reason: refundResult.refundReason,
        refund_type: refundResult.refundType,
        wechat_refund_id: wechatRefundResult.refundId,
        refund_status: wechatRefundResult.status,
        refund_time: new Date().toISOString(),
        calculation: refundResult.calculation
      };
    }

    // 更新订单信息
    const formattedEndTime = formatDateTimeForMySQL(actual_end_time);

    const updateFields = [
      'actual_end_time = ?',
      'status = ?',
      'updated_at = NOW()'
    ];
    const updateParams = [
      formattedEndTime,
      'completed'
    ];

    // 存储退款信息
    if (refundInfo) {
      const paymentInfo = {
        original_method: order.payment_method,
        refund_info: refundInfo
      };
      updateFields.push('payment_method = ?');
      updateParams.push(JSON.stringify(paymentInfo));
    }

    updateParams.push(orderId);

    const updateQuery = `
      UPDATE orders
      SET ${updateFields.join(', ')}
      WHERE id = ?
    `;

    await query(updateQuery, updateParams);

    console.log(`✅ 提前离场处理完成 - 订单: ${order.order_number}${refundInfo ? ', 退款: ' + refundInfo.refund_amount + '元' : ', 无退款'}`);

    res.json({
      success: true,
      message: refundInfo ? 
        `提前离场处理完成，退款${refundInfo.refund_amount}元` : 
        '提前离场处理完成，无需退款',
      data: {
        order_id: orderId,
        order_number: order.order_number,
        status: 'completed',
        refund_info: refundInfo,
        calculation: refundResult
      }
    });

  } catch (error) {
    console.error('处理提前离场错误:', error);
    res.status(500).json({
      success: false,
      message: '处理提前离场失败，请稍后重试'
    });
  }
};

/**
 * 处理延迟离场补款
 */
const processLateDeparture = async (req, res) => {
  try {
    const { orderId } = req.params;
    const { actual_end_time } = req.body;
    const userId = req.user.id;

    console.log(`⏰ 处理延迟离场 - 订单ID: ${orderId}, 用户ID: ${userId}`);

    // 验证订单
    const orderQuery = `
      SELECT 
        id, order_number, status, final_amount, total_amount, discount_amount,
        planned_start_time, planned_end_time, actual_start_time, actual_end_time,
        parking_lot_id, transaction_id, payment_method, paid_at
      FROM orders
      WHERE id = ? AND user_id = ?
    `;

    const orders = await query(orderQuery, [orderId, userId]);

    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在或无权限访问'
      });
    }

    const order = orders[0];

    // 检查订单状态
    if (order.status !== 'in_progress') {
      return res.status(400).json({
        success: false,
        message: '只有进行中的订单才能处理延迟离场'
      });
    }

    const actualEndTime = new Date(actual_end_time);
    const plannedEndTime = new Date(order.planned_end_time);

    // 检查是否确实是延迟离场
    if (actualEndTime <= plannedEndTime) {
      return res.status(400).json({
        success: false,
        message: '新离场时间必须晚于预计离场时间'
      });
    }

    // 计算新的停车费用（从实际入场时间到新离场时间）
    const actualStartTime = new Date(order.actual_start_time || order.planned_start_time);

    // 使用价格引擎重新计算费用
    const pricingEngine = require('../utils/pricingEngine');
    const newPriceResult = await pricingEngine.calculatePrice(
      order.parking_lot_id,
      actualStartTime,
      actualEndTime
    );

    if (!newPriceResult.success) {
      return res.status(400).json({
        success: false,
        message: `费用计算失败: ${newPriceResult.error}`
      });
    }

    // 计算需要补交的金额（新总费用 - 优惠券折扣 - 已支付金额）
    const newTotalAmount = newPriceResult.total_amount;
    const paidAmount = parseFloat(order.final_amount);
    const discountAmount = parseFloat(order.discount_amount) || 0;
    // 计算应付金额：新总费用 - 优惠券折扣（优惠券永久有效）
    const shouldPayAmount = Math.max(0, newTotalAmount - discountAmount);
    const additionalAmount = Math.max(0, Math.round((shouldPayAmount - paidAmount) * 100) / 100);

    console.log(`💰 延后离场费用计算 - 订单: ${order.order_number}`);
    console.log(`   原费用: ${paidAmount}元`);
    console.log(`   新费用: ${newTotalAmount}元`);
    console.log(`   需补款: ${additionalAmount}元`);

    // 更新订单信息
    const formattedEndTime = formatDateTimeForMySQL(actual_end_time);

    const updateFields = [
      'planned_end_time = ?',  // 更新预计离场时间为新选择的时间
      'total_amount = ?',      // 更新总金额为新计算的金额
      'updated_at = NOW()'
    ];
    const updateParams = [
      formattedEndTime,
      newTotalAmount
    ];

    // 如果需要补款，设置为待补款状态；否则直接完成
    if (additionalAmount > 0) {
      updateFields.push('status = ?');
      updateParams.push('pending_additional_payment');
    } else {
      updateFields.push('status = ?', 'actual_end_time = ?');
      updateParams.push('completed', formattedEndTime);
    }

    updateParams.push(orderId);

    const updateQuery = `
      UPDATE orders
      SET ${updateFields.join(', ')}
      WHERE id = ?
    `;

    await query(updateQuery, updateParams);

    console.log(`✅ 延迟离场处理完成 - 订单: ${order.order_number}${additionalAmount > 0 ? ', 需补款: ' + additionalAmount + '元' : ', 无需补款'}`);

    res.json({
      success: true,
      message: additionalAmount > 0 ?
        `延迟离场处理完成，需补款${additionalAmount}元` :
        '延迟离场处理完成，无需补款',
      data: {
        order_id: orderId,
        order_number: order.order_number,
        status: additionalAmount > 0 ? 'pending_additional_payment' : 'completed',
        additional_amount: additionalAmount,
        new_total_amount: newTotalAmount,
        paid_amount: paidAmount,
        new_end_time: formattedEndTime,
        calculation: {
          original_amount: paidAmount,
          new_total_amount: newTotalAmount,
          additional_payment: additionalAmount,
          start_time: actualStartTime.toISOString(),
          end_time: actualEndTime.toISOString()
        }
      }
    });

  } catch (error) {
    console.error('处理延迟离场错误:', error);
    res.status(500).json({
      success: false,
      message: '处理延迟离场失败，请稍后重试'
    });
  }
};

/**
 * 查询退款状态
 */
const queryRefundStatus = async (req, res) => {
  try {
    const { orderId } = req.params;
    const userId = req.user.id;

    // 获取订单信息
    const orderQuery = `
      SELECT id, order_number, payment_method, status
      FROM orders
      WHERE id = ? AND user_id = ?
    `;

    const orders = await query(orderQuery, [orderId, userId]);

    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    const order = orders[0];
    let refundInfo = null;

    // 解析退款信息
    try {
      const paymentInfo = JSON.parse(order.payment_method);
      if (paymentInfo.refund_info) {
        refundInfo = paymentInfo.refund_info;
        
        // 查询微信支付退款状态
        if (refundInfo.refund_number) {
          const wechatResult = await WechatPayService.queryRefund(refundInfo.refund_number);
          if (wechatResult.success) {
            refundInfo.current_status = wechatResult.data?.status || refundInfo.refund_status;
          }
        }
      }
    } catch (error) {
      // payment_method不是JSON格式，可能没有退款信息
    }

    res.json({
      success: true,
      data: {
        order_id: orderId,
        order_number: order.order_number,
        order_status: order.status,
        refund_info: refundInfo
      }
    });

  } catch (error) {
    console.error('查询退款状态错误:', error);
    res.status(500).json({
      success: false,
      message: '查询失败'
    });
  }
};

module.exports = {
  processEarlyDeparture,
  processLateDeparture,
  queryRefundStatus
};
